﻿using Cl.Utils.Helper;
using Cl.Utils;
using Cl.WebApi.Authorization.CustomerAttributes;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;

namespace Cl.WebApi.Controllers
{
    /// <summary>
    /// 混合控制器基类，通过自定义特性校验
    /// </summary>
    public class ClientMingleController : BaseController
    {
        /// <summary>
        /// 执行时操作
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);

            // 如果基类已经设置了结果，则直接返回
            if (context.Result != null)
            {
                return;
            }

            if (GlobalService.SystemConfigGlobal.EnableSafeMode)
            {
                // 忽略权限验证
                if (JwtHelper.HasAllowAnonymous(context))
                {
                    base.OnActionExecuting(context);
                    return;
                }

                // 校验用户是否能用控制器的方法
                var methodInfo = context.ActionDescriptor as Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor;
                if (methodInfo != null)
                {
                    // 查找CustomValueAttribute属性
                    var customValueAttributes = methodInfo.MethodInfo.GetCustomAttributes(typeof(AuthorizeActionAttribute), false);
                    foreach (var attr in customValueAttributes)
                    {
                        var authorizeActionAttr = attr as AuthorizeActionAttribute;
                        if (authorizeActionAttr != null && authorizeActionAttr.ClientType != GlobalUserManager.GlobalUserInfo.ClientType)
                        {
                            context.Result = new ContentResult() { StatusCode = StatusCodes.Status403Forbidden, Content = "权限不足" };
                            return;
                        }
                    }
                }
            }
        }
    }
}
